package fe;

import java.lang.reflect.Constructor;
import java.util.ArrayList;

import fe.FeatureConfig.FeatureType;

public class SchemaManager {
	private FeatureConfig featureConfig;
	private FeatureType featureType;
	private FeatureExtractorBase[] featureExtractors = null;
	private boolean keepFeature(FeatureType type) {
		return type != FeatureType.USELESS && (featureType == FeatureType.PRODUCTION || featureType == type);
	}
	
	public void initManager(FeatureConfig config, FeatureType type) throws Exception{
		this.featureConfig = config;
		this.featureType = type;
	
		ArrayList<String> featureNames = featureConfig.getFeatureNames();
		ArrayList<FeatureType> featureTypes = featureConfig.getFeatureTypes();
		featureExtractors = new FeatureExtractorBase[featureNames.size()];
		for (int i = 0; i < featureNames.size(); ++i) {
			if (keepFeature(featureTypes.get(i))) {
				featureExtractors[i] = createFeatureExtractorByName(featureNames.get(i));
				featureExtractors[i].initFeature();
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	private FeatureExtractorBase createFeatureExtractorByName(String featureName) throws Exception{
		FeatureExtractorBase base;
		Class cls = Class.forName(featureName);
		Constructor ct = cls.getConstructor(new Class[]{FeatureManager.class});
		base = (FeatureExtractorBase)ct.newInstance(new Object[]{null});
		return base;
	}
	
	public void checkFeaturesStr(String[] features) throws Exception{
		ArrayList<FeatureType> featureTypes = featureConfig.getFeatureTypes();
		for (int i = 0; i < featureExtractors.length; ++i) {
			if (keepFeature(featureTypes.get(i)))
				featureExtractors[i].checkFeature(features[i]);
		}		
	}
	
	public String getFeatureSchema() {
		StringBuilder builder = new StringBuilder();
		builder.append("@relation 'click_prediction_data'\n");
		ArrayList<FeatureType> featureTypes = featureConfig.getFeatureTypes();
		for (int i = 0; i < featureExtractors.length; ++i) {
			if (keepFeature(featureTypes.get(i))) {
				builder.append(featureExtractors[i].getSchema());
				builder.append("\n");
			}
		}
		builder.append("@data\n");
		return builder.toString();		
	}
}
